package com.study.thirdpartyeventconsumer.controller;

import com.study.thirdpartyeventconsumer.constant.MailType;
import com.study.thirdpartyeventconsumer.entity.Student;
import com.study.thirdpartyeventconsumer.mapper.StudentMapper;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {
    @Autowired
    private StudentMapper studentMapper;

    @GetMapping(value = "/create")
    public void forwardRequest() throws IOException {
        Student student = new Student();
        student.setId(UUID.randomUUID().toString().replace("-", ""));
        student.setName("小明");
        student.setAge(0);
        student.setAddress("");
        student.setBirthday(new Date());
        student.setMailType(MailType.qq);
        studentMapper.insert(student);
    }

    //查询学生列表接口
    @GetMapping(value = "/getList")
    public List<Student> list() {
        return studentMapper.selectList(null);
    }

    //查询学生列表接口
    @GetMapping(value = "/download")
    public void download(HttpServletResponse response) throws FileNotFoundException {
        String fileName = "LinkedIn_审核视频.mp4";
        File file = new File(fileName);

        if (!file.exists()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // 设置响应头
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.setHeader("Content-Length", String.valueOf(file.length()));
        response.setHeader("Accept-Ranges", "bytes");

        // 支持分块传输
//        response.setHeader("Transfer-Encoding", "chunked");

        try (FileInputStream fileInputStream = new FileInputStream(file);
             OutputStream outputStream = response.getOutputStream()) {

            byte[] buffer = new byte[8192]; // 8KB chunks
            int bytesRead;
            long totalBytesRead = 0;
            long fileSize = file.length();

            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
                Thread.sleep(200); // 模拟网络延迟（生产环境删除）
                outputStream.flush();

                totalBytesRead += bytesRead;

                // 可选：打印进度到日志
                double progress = (double) totalBytesRead / fileSize * 100;
                if (totalBytesRead % (1024 * 1024) == 0) { // 每1MB打印一次
                    log.info("下载进度: {:.2f}%", progress);
                }

                // 模拟网络延迟（生产环境删除）
                // Thread.sleep(10);
            }

        } catch (Exception e) {
            log.error("文件下载失败", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}
